// components/user-header/index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const {updateAvatarUrl} = require('../../apiConfig/apiList/luban')
Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
      phone: '',

    },
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),

  },

  /**
   * 组件的方法列表
   */
  methods: {
    getUserData(){
      let that = this;
      let data = wx.getStorageSync('userInfo') || {};
      let { loginUrl, phone, nickName} = wx.getStorageSync('loginData').loginUser || {};
      this.setData({
        "userInfo.avatarUrl": loginUrl || data.avatarUrl,
        "userInfo.nickName": nickName || data.nickName,
        "userInfo.phone": that.maskPhoneNum(phone),
      })
    },
    maskPhoneNum(num){
      if(!num) return '';
      return num.slice(0, 3) + `****` + num.slice(num.length - 4);
    },
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail
      const { nickName } = this.data.userInfo
      this.setData({
        "userInfo.avatarUrl": avatarUrl,
        "userInfo.nickName": nickName,
      },()=>{
        this.updateAvatarUrl({'loginUrl':avatarUrl})
        
      })
    },
    updateAvatarUrl(params){
      updateAvatarUrl(params).then(res=>{
        if(res.code == 200){
          const { loginType = '', maOpenId, maSessionKey, maUnionId, toBind, authToken = '',schoolName = '' ,loginUser, subscribeStatus = '' } = res.data;
          wx.setStorageSync('loginData',  {loginType, maOpenId, maSessionKey, maUnionId, toBind, authToken,schoolName, loginUser, subscribeStatus });
        }
        console.log('saveDatares', res);
      })
    },
    getUserProfile(e) {
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log(res)
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    },

  },
  attached(){
    this.getUserData();
  },
})